<template>
  <a-spin :spinning="confirmLoading" style="background: #fff">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">
          <!-- 基本信息 -->
          <a-collapse-panel key="1" header="基本信息">
            <a-row :gutter="48">
              <a-col :span="12" :hidden="true">
                <a-form-model-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle">
                  <a-input :disabled="formDisabled" v-model="model.bpmBizTitle" placeholder="请输入标题" ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purchaseBill">
                  <a-input :disabled="formDisabled" v-model="model.purchaseBill" placeholder="请输入单据编号" disabled></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposer">
                  <select-user-by-dep
                    placeholder="请选择申请人"
                    v-model="model.proposer"
                    disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="departId">
                  <j-select-depart placeholder="请选择申请部门" :disabled="formDisabled" v-model="model.departId" disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
                  <j-date
                    placeholder="请选择申请时间"
                    v-model="model.createTime"
                    :show-time="true"
                    date-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                    disabled/>
                </a-form-model-item>
              </a-col>
              <!-- <a-col :span="12">
                <a-form-model-item label="领用人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="employeeId">
                  <select-user-by-dep
                        placeholder="请选择领用人"
                        :disabled="formDisabled"
                        v-model="model.employeeId"/>
                </a-form-model-item>
              </a-col> -->
              <a-col :span="12">
                <a-form-model-item label="领用团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamId">
                  <select-team-input placeholder="请选择团队" :disabled="formDisabled" v-model="model.teamId" :tdlx="3" />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
                  <a-textarea :disabled="formDisabled" :max-length="500" v-model="model.remark" rows="4" placeholder="请输入备注"/>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="2" header="物品领用明细">
            <erp-purchase-recipients-detail-list ref="recipientsDetail" :disabled="formDisabled"></erp-purchase-recipients-detail-list>
          </a-collapse-panel>
          <!-- 附件信息 -->
          <a-collapse-panel key="3" header="附件信息">
            <a-row :gutter="48">
              <a-col :span="24">
                <a-form-model-item prop="purchaseFile">
                  <j-upload v-if="!formDisabled" :disabled="formDisabled" v-model="model.purchaseFile"></j-upload>
                  <a-button v-else icon="download" @click="viewFile(model.purchaseFile)">文件列表</a-button>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <!-- <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
            <a-button @click="submitForm">提 交</a-button>
          </a-col> -->
        </a-collapse>
      </a-form-model>
      <common-flow-list v-if="formBpm && model.bpmStatus !== '1'" :formData="formData" style="margin-top: 10px"></common-flow-list>
      <view-file-modal ref="viewFileModal"></view-file-modal>
    </j-form-container>
    <a-row :gutter="48">
      <a-col :span="24" style="text-align: center;margin-top: 15px">
        <a-button type="primary" v-if="formBpm" :style="{ marginRight: showFlowSubmitButton?'10px':'0px' }" @click="onPrint">打印</a-button>
        <a-button @click="submitForm('submit')" v-if="showFlowSubmitButton">提 交</a-button>
      </a-col>
    </a-row>
    <ErpPurchaseRecipientsFormPrint v-if="formBpm" class="print_style" id="recipientsContent" :formData="model" :formDataHistory="formData"></ErpPurchaseRecipientsFormPrint>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
  import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
  import SelectMaterialInput from '@/views/scy/components/SelectMaterialInput'
  import { mapGetters } from 'vuex';
  import moment from 'moment';
  import { viewFile } from '@/utils/util'
  import ViewFileModal from '@/views/scy/components/ViewFileModal'
  import ErpPurchaseRecipientsDetailList from './reference/ErpPurchaseRecipientsDetailList.vue'
  import CommonFlowList from '@/views/components/CommonFlowList.vue';
  import Print from '@/utils/print/printarea.js';
  import ErpPurchaseRecipientsFormPrint from './ErpPurchaseRecipientsFormPrint.vue'; // 打印定制
  export default {
    name: 'ErpPurchaseRecipientsForm',
    mixins: [viewFile],
    components: {
      ErpPurchaseRecipientsDetailList,
      SelectUserByDep,
      SelectTeamInput,
      SelectMaterialInput,
      ViewFileModal,
      CommonFlowList,
      ErpPurchaseRecipientsFormPrint
    },
    props: {
      // 流程表单data
      formData: {
        type: Object,
        default: () => {},
        required: false
      },
      // 表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        activeKey: ['1', '2', '3'],
        model: {
          deliveryStorage: 0,
          checkStatus: 0,
          purchaseBill: null
        },
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 }
        },
        confirmLoading: false,
        validatorRules: {
          purchaseBill: [
              { required: true, message: '单据编号不能为空!', trigger: 'blur' }
          ],
          // employeeId: [
          //     { required: true, message: '请选择领用人!', trigger: 'change'},
          // ],
          // departId: [
          //     { required: true, message: '请选择领用部门!', trigger: 'change'},
          // ],
          teamId: [
              { required: true, message: '请选择领用团队!', trigger: 'change' }
          ]
        },
        url: {
          add: '/api/erp/purchase/recipients/erpPurchaseRecipients/add',
          edit: '/api/erp/purchase/recipients/erpPurchaseRecipients/edit',
          queryById: '/api/erp/purchase/recipients/erpPurchaseRecipients/queryById',
          gainBillNo: '/api/erp/purchase/recipients/erpPurchaseRecipients/gainBillNo'
        },
        userName: ''
      }
    },
    computed: {
      formDisabled() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return true
          }
        }
        return false
      }
    },
    created () {
       // 备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      // 如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
    },
    methods: {
      ...mapGetters(['userInfo']),
      getBillNo () {
        const that = this
        getAction(this.url.gainBillNo).then((res) => {
          if (res.success) {
            that.model.purchaseBill = res.result// 单据编号
            that.model.bpmBizTitle = that.userName + '-' + that.model.purchaseBill// 标题
          }
        })
      },
      add () {
        this.edit(this.modelDefault);
        this.userName = this.userInfo().empName;// 当前登录人名称
        this.model.proposer = this.userInfo().empId; // 当前登录人
        this.model.departId = this.userInfo().deptId; // 当前登录人部门
        this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
        this.getBillNo() // 获取单据编号
      },
      edit (record) {
        this.$refs['form'].clearValidate();
        this.model = Object.assign({}, record);
        if (this.model.id) {
          this.$refs.recipientsDetail.loadData(1, this.model.id)
        } else {
          this.$refs.recipientsDetail.dataSource = []
        }
        this.visible = true;
      },
      // 渲染流程表单数据
      showFlowData() {
        if (this.formBpm === true) {
          let params = { id: this.formData.dataId };
          getAction(this.url.queryById, params).then((res) => {
            if (res.success) {
              this.edit(res.result);
            }
          });
        }
      },
      submitForm (type) {
        const that = this;
        if (type == 'draft') {
          // 代表保存草稿不做校验
          this.submit(type)
        } else if (type == 'submit') {
          let details = this.$refs.recipientsDetail.submitForm()
          if (!details.length > 0) {
            this.$message.warning('请添加物品领用明细信息！');
            this.$emit('unButtonDisable');
            return false
          }
          // 判断数据有没有填写领用数量
          var isRecipientsNum = details.some(item => !item.recipientsNum);
          // var isRemark = details.some(item => !item.remark);
          if (isRecipientsNum) {
            // 当为true说明有值领用数量没有填写
            this.$message.warning('请填写物品领用明细信息中的领用数量！');
            this.$emit('unButtonDisable');
            return false
          }
          // if (isRemark) {
          //   // 当为true说明有值领用用途没有填写
          //   this.$message.warning('请填写物品领用明细信息中的领用用途！');
          //   this.$emit('unButtonDisable');
          //   return false
          // }
          // 触发表单验证
          this.$refs.form.validate(valid => {
            if (valid) {
              that.submit(type)
            } else {
              that.$emit('unButtonDisable')
            }
          })
        } else {
          console.log('传参数，保存：draft，提交：submit')
        }
      },

      submit (type) {
        const that = this;
        let details = this.$refs.recipientsDetail.submitForm() || []
        that.confirmLoading = true;
        let httpurl = '';
        let method = '';
        if (!this.model.id) {
          httpurl += this.url.add;
          method = 'post';
        } else {
          httpurl += this.url.edit;
          method = 'put';
        }
        this.model.detailList = details
        httpAction(httpurl, this.model, method).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            if (method == 'post') {
              that.model.id = res.result;
            }
            that.$emit('ok', type, that.model);
          } else {
            that.$message.warning(res.message);
            that.$emit('unButtonDisable');
          }
        }).catch((error) => {
          that.$emit('unButtonDisable', error);
        }).finally(() => {
          that.confirmLoading = false;
        })
      },

      // 点击打印
      onPrint () {
        let print = new Print({
          el: '#recipientsContent',
          popTitle: '物品领用申请详情 · 禾美环保',
          endCallback() {

          }
        })
      }
    }
  }
</script>
<style>
  @import "../../../../../utils/print.css";
  .print_style{
    position: absolute;
    top: 0;
    z-index: -1111;
  }
</style>
